import { createSlice } from '@reduxjs/toolkit';

// 存储到 localStorage（根据数据类型判断是否需要 JSON 序列化）
const setLocalStorage = (key, value) => {
    if (typeof value === 'object') {
        localStorage.setItem(key, JSON.stringify(value));
    } else {
        localStorage.setItem(key, value);
    }
};

// 从 localStorage 获取数据（根据需要是否解析 JSON）
const getLocalStorage = (key, isJSON = false) => {
  const value = localStorage.getItem(key);
  if (!value) return null; // 如果 localStorage 中没有该键，返回 null
  try {
      return isJSON ? JSON.parse(value) : value;
  } catch (error) {
      console.error(`Error parsing JSON from localStorage for key "${key}":`, error);
      return null; // 解析失败时返回 null
  }
};


// 移除 localStorage 数据
const clearLocalStorage = (key) => {
    localStorage.removeItem(key);
};

// 检查 token 是否过期
const isTokenExpired = (expiration) => {
    const currentTime = new Date().getTime();
    return expiration && currentTime > new Date(expiration).getTime();
};

// 初始化状态
const initialState = {
    token: getLocalStorage('token'), 
    username: getLocalStorage('username') || '',
    roles: getLocalStorage('roles', true) || [],
    permissions: getLocalStorage('permissions', true) || [],
    menus: getLocalStorage('menus', true) || [],
    expiration: getLocalStorage('expiration') || null,
    isAuthenticated: !!getLocalStorage('token') && !isTokenExpired(getLocalStorage('expiration')),
    isForceRelogin: getLocalStorage('isForceRelogin') === 'true' // 判断是否需要强制重新登录
  };
  
  // 创建 authSlice
  const authSlice = createSlice({
    name: 'auth',
    initialState,
    reducers: {
      // 登录操作
      login(state, action) {
        const { token, username, roles, permissions, menus, expiration } = action.payload;
        state.token = token;
        state.username = username;
        state.roles = roles;
        state.permissions = permissions;
        state.menus = menus;
        state.expiration = expiration;
        state.isAuthenticated = true;
        state.isForceRelogin = false;
  
        // 将数据存储到 localStorage
        setLocalStorage('token', token);
        setLocalStorage('username', username);
        setLocalStorage('roles', roles);
        setLocalStorage('permissions', permissions);
        setLocalStorage('menus', menus);
        setLocalStorage('expiration', expiration);
        setLocalStorage('isForceRelogin', false);
      },
      
      // 登出操作
      logout(state) {
        state.token = null;
        state.username = '';
        state.roles = [];
        state.permissions = [];
        state.menus = [];
        state.expiration = null;
        state.isAuthenticated = false;
        state.isForceRelogin = false;
  
        // 从 localStorage 移除数据
        clearLocalStorage('token');
        clearLocalStorage('username');
        clearLocalStorage('roles');
        clearLocalStorage('permissions');
        clearLocalStorage('menus');
        clearLocalStorage('expiration');
        clearLocalStorage('isForceRelogin');
      },
  
      // 处理强制重新登录
      forceRelogin(state) {
        state.isForceRelogin = true;
        setLocalStorage('isForceRelogin', true);
      }
    }
  });
  
  // 导出操作（actions）
  export const { login, logout, forceRelogin } = authSlice.actions;
  
  // 导出选择器（selectors）
  export const selectAuth = (state) => state.auth;
  export const selectIsAuthenticated = (state) => state.auth.isAuthenticated;
  export const selectUserRoles = (state) => state.auth.roles;
  export const selectMenus = (state) => state.auth.menus;
  export const selectIsForceRelogin = (state) => state.auth.isForceRelogin;
  
  export default authSlice.reducer;
  